package com.gugee.ins.data.task.mark.service;

import com.gugee.ins.common.dto.RankTaskParam;
import com.gugee.ins.common.dal.service.mark.InsRkBloggerAdecMonthDao;
import com.xiguaji.boot.toolkit.DateTimeUtils;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.List;


/**
 *  ins大博主分类、广告帖子总参与数月榜单
 * @author huangxin
 */
@Component
@Slf4j
public class InsRkBloggerAdecMonthSvc extends AbstractMarkRankProducerHandler {
    /**
     *
     */
    @Autowired
    InsRkBloggerAdecMonthDao insRkBloggerAdecMonthDao;

    /**
     * 处理ins大博主分类、广告帖子总参与数月榜单
     */
    @Override
    public void handleRank(RankTaskParam taskParam) {
        // 查找一级分类
        List<String> categoryList = getCategory(taskParam.getCategory(),true);

        Calendar calendar = Calendar.getInstance();

        // 设置时间
        if(!StringUtils.isEmpty(taskParam.getDateCode())){
            calendar.setTimeInMillis(getDateTime(taskParam.getDateCode()));
        }

        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        int lastDayOfRankMonth = Integer.parseInt(DateTimeUtils.formatSecond(calendar.getTimeInMillis() / 1000,
                "yyyyMMdd",taskConfig.getInsBloggerMarkDaytimeZone()));
        int rankMonth = lastDayOfRankMonth / 100;
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        int lastRankMonth = Integer.parseInt(DateTimeUtils.formatSecond(calendar.getTimeInMillis() / 1000,
                "yyyyMM",taskConfig.getInsBloggerMarkDaytimeZone()));

        // 分类月周榜
        if(categoryList != null && !categoryList.isEmpty()){
            for(String category : categoryList){
                markRank(rankMonth,lastRankMonth,category);
            }
        }
    }

    /**
     *
     * @param rankMonth
     * @param lastRankMonth
     * @param category
     */
    public void markRank(int rankMonth,int lastRankMonth,String category){
        try{
            insRkBloggerAdecMonthDao.insertRkBloggerAdecMonth(rankMonth,lastRankMonth,category);
        }catch (Exception e){
            log.info("ins大博主分类、广告帖子总参与数月榜单 生成失败 rankMonth:{},category:{},msg:{}", rankMonth,category,e.getMessage());
            XxlJobLogger.log("ins大博主分类、广告帖子总参与数月榜单 生成失败 rankMonth:{},category:{},msg:{}",rankMonth,category,e.getMessage());
        }
    }
}
